package cas;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author dengzhiyuan
 * @version 1.0
 * @time 2021/3/15 18:51
 */
public class VisitTimes {

    static int count = 0;

    /**
     * Q：耗时太长的原因是什么呢？
     * A: 程序中的request方法使用synchronized关键字修饰，保证了并发情况。request方法同一时刻只允许一个线程进入，request加锁相当于串行执行了。
     * @author dengzhiyuan
     * @version 1.0
     * @time 2021/3/22 11:38
     * @param 
     * @return 
     */
    public synchronized static void request() throws InterruptedException{
        TimeUnit.MILLISECONDS.sleep(5);
        /**
         * Q:分析一下问题出在那里
         * A:count++  操作实际上是由3步来完成的（jvm执行引擎）
         * 1.获取count的值，记做A:A=count
         * 2.将A值+1，得到B:B=A+1
         * 3.将B值赋值给count
         */
        count++;
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        int threadSize = 100;
        CountDownLatch countDownLatch = new CountDownLatch(threadSize);
        for (int t = 0; t < threadSize; t++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        for (int i = 0; i < 10; i++) {
                            request();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
            thread.start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+ "，耗时间="+(System.currentTimeMillis()-startTime)+",count="+count);
    }



}
